package com.tianji.login.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.token.TokenStore;

/**
 * @Author jia
 * @Description 资源服务器用来保护需要授权访问的资源，如 /coupon/** 和 /course/**
 * @Date 15:00 2024-10-04
**/
@Configuration
@EnableResourceServer
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {

    public static final String RESOURCE_ID = "tianji";

    @Autowired
    private TokenStore tokenStore;

    @Override
    public void configure(ResourceServerSecurityConfigurer resources) {
        resources.resourceId(RESOURCE_ID) // 资源 ID
                .tokenStore(tokenStore) // 令牌存储
                .stateless(true); // 无状态
    }

    @Override
    public void configure(HttpSecurity http) throws Exception {
        http.csrf().disable()
                .authorizeRequests()
                .antMatchers("/coupons/**").hasAuthority("ROLE_COUPON_ADMIN") // 需要 "ROLE_COUPON_ADMIN" 权限
                .antMatchers("/orders/**").hasAuthority("ROLE_COURSE_ADMIN") // 需要 "ROLE_COURSE_ADMIN" 权限
                .anyRequest().authenticated(); // 其他请求需要认证
    }
}
